package com.mtw.bbs.common.web.filter;

import com.alibaba.fastjson.JSON;
import com.mtw.bbs.common.core.constant.AuthConstant;
import com.mtw.bbs.common.core.security.UserDetails;
import com.mtw.bbs.common.core.security.context.SecurityContext;
import com.mtw.bbs.common.core.security.context.SecurityContextHolder;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.io.PrintWriter;
/**
 * 基础权限认证过滤器
 */
@Slf4j
@WebFilter("/*")
public class BaseRequestAuthFilter implements Filter {



    @Override
    public void init(FilterConfig filterConfig) {}




    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 预检请求放行
        if(request.getMethod().matches(HttpMethod.OPTIONS.name())){
            filterChain.doFilter(request, response);
        }

        String authed = request.getHeader(AuthConstant.SERVICE_AUTH_KEY);
        // 未认证
        if (StringUtils.isBlank(authed)) {
            returnNoAuth(response, "请登录");
            return;
        }
        // 认证失败
        if (AuthConstant.AuthedType.FAIL.getName().equals(authed)) {
            returnNoAuth(response, "认证信息错误");
            return;
        }
        // 保存当前用户
        String userJson = request.getHeader(AuthConstant.AUTH_USER_KEY);
        if (StringUtils.isNotBlank(userJson) && !AuthConstant.AuthedType.IGNORE.getName().equals(authed)) {
            UserDetails currentUser = JSON.parseObject(userJson, UserDetails.class);
            SecurityContext context = SecurityContextHolder.getContext();
            context.setAuthentication(currentUser);
        }

        filterChain.doFilter( servletRequest,servletResponse);
    }

    /**
     * 自定义返回无权限
     */
    private void returnNoAuth(HttpServletResponse response, String msg) {

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = response.getWriter()) {
            out.print(StringUtils.isNotBlank(msg) ? msg : "无访问权限");
        } catch (IOException e) {
            log.error("sendResponse error：", e);
        }
    }

    @Override
    public void destroy() {}


}
